<?php

namespace ruoyi\admin;

use Exception;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class Utils {

    /**
     * 检查是否为内部IP地址
     */
    public static function internalIp(?string $ip): bool {
        return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE|FILTER_FLAG_NO_RES_RANGE) == false;
    }

    /**
     * 获取地址
     */
    public static function getRealAddressByIP(?string $ip): string {
        if (Utils::internalIp($ip)) { return '内网IP'; }
        $isAddressEnabled = true;       // todo 获取地址开关
        if ($isAddressEnabled) {
            // $url = 'http://whois.pconline.com.cn/ipJson.jsp?ip=$ip&json=true';
            $url = 'https://ip.taobao.com/outGetIpInfo';
            try {
                $data = Http::connectTimeout(2)->timeout(2)->asForm()->post($url, ['ip'=>$ip, 'accessKey'=>'alibaba-inc'])->json('data');
                if (empty($data)) { return 'FAIL'; }
                $addr_isp = strtoupper($data['region']) == 'XX' ? $data['country'] : ($data['region'] == $data['city'] ? $data['region'] : "{$data['region']} {$data['city']}");
                $addr_isp .= strtoupper($data['isp']) == 'XX' ? '' : " {$data['isp']}";
                return trim($addr_isp);
            } catch(Exception $e) {
                Log::error($e);
                return 'EXCEP';
            }
        }
        return 'XX XX';
    }

    /**
     * 生成BCryptPasswordEncoder密码
     */
    public static function encryptPassword($password): string {
        return bcrypt($password);
    }

    /**
     * 判断密码是否相同
     */
    public static function matchesPassword($raw, $encoded) {
        return password_verify($raw, $encoded);
    }

}